package com.zh.common.utils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
 
public class EntityMapUtil {
 
    /**
     * 将实体类转换为Map
     *
     * @param obj 实体类对象
     * @return Map
     */
    public static Map<String, Object> entityToMap(Object obj) {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(obj));
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return map;
    }
 
    /**
     * 将Map转换为实体类
     *
     * @param map  Map对象
     * @param clazz 实体类的Class对象
     * @return 实体类对象
     */
    public static <T> T mapToEntity(Map<String, Object> map, Class<T> clazz) {
        T obj = null;
        try {
            obj = clazz.newInstance();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                field.set(obj, map.get(field.getName()));
            }
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return obj;
    }
}